import { prisma } from '../db/prisma';
import { createSuccessResponse, createErrorResponse } from '../utils/response';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';

export class AuthService {
  /**
   * 客户经理登录
   */
  static async managerLogin(input: {
    username: string;
    password: string;
  }) {
    try {
      // 查找客户经理
      const manager = await prisma.manager.findUnique({
        where: { username: input.username },
      });

      if (!manager) {
        return createErrorResponse('用户名或密码错误');
      }

      // 验证密码
      const isPasswordValid = await bcrypt.compare(input.password, manager.passwordHash);
      if (!isPasswordValid) {
        return createErrorResponse('用户名或密码错误');
      }

      // 生成JWT token
      const token = jwt.sign(
        { 
          managerId: manager.id, 
          username: manager.username,
          type: 'manager'
        },
        process.env.JWT_SECRET || 'default-secret',
        { expiresIn: '7d' }
      );

      // 返回用户信息（不包含密码）
      const { passwordHash, ...managerInfo } = manager;

      return createSuccessResponse({
        manager: managerInfo,
        token,
      }, '登录成功');
    } catch (error) {
      console.error('客户经理登录失败:', error);
      return createErrorResponse('登录失败');
    }
  }

  /**
   * 验证token并获取客户经理信息
   */
  static async verifyManagerToken(token: string) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET || 'default-secret') as any;
      
      if (decoded.type !== 'manager') {
        return createErrorResponse('无效的token类型');
      }

      const manager = await prisma.manager.findUnique({
        where: { id: decoded.managerId },
      });

      if (!manager) {
        return createErrorResponse('用户不存在');
      }

      const { passwordHash, ...managerInfo } = manager;

      return createSuccessResponse({
        manager: managerInfo,
      }, '验证成功');
    } catch (error) {
      console.error('Token验证失败:', error);
      return createErrorResponse('Token验证失败');
    }
  }

  /**
   * 获取客户经理的基本信息和统计数据
   */
  static async getManagerProfile(managerId: number) {
    try {
      const manager = await prisma.manager.findUnique({
        where: { id: managerId },
        include: {
          clientAssignments: {
            include: {
              client: {
                include: {
                  serviceAssignments: {
                    include: {
                      service: true,
                    },
                  },
                },
              },
            },
          },
        },
      });

      if (!manager) {
        return createErrorResponse('客户经理不存在');
      }

      // 统计客户数量
      const totalClients = manager.clientAssignments.length;

      // 统计服务项目数量
      const serviceIds = new Set();
      manager.clientAssignments.forEach(assignment => {
        assignment.client.serviceAssignments.forEach(sa => {
          serviceIds.add(sa.serviceId);
        });
      });
      const totalServices = serviceIds.size;

      // 获取本月工作日志数量
      const now = new Date();
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);

      const monthlyWorkLogs = await prisma.workLog.count({
        where: {
          managerId: managerId,
          completionDate: {
            gte: monthStart,
            lte: monthEnd,
          },
        },
      });

      const { passwordHash, ...managerInfo } = manager;

      return createSuccessResponse({
        manager: managerInfo,
        stats: {
          totalClients,
          totalServices,
          monthlyWorkLogs,
        },
      }, '获取个人信息成功');
    } catch (error) {
      console.error('获取客户经理信息失败:', error);
      return createErrorResponse('获取个人信息失败');
    }
  }

  /**
   * 修改客户经理密码
   */
  static async changePassword(input: {
    managerId: number;
    oldPassword: string;
    newPassword: string;
  }) {
    try {
      const manager = await prisma.manager.findUnique({
        where: { id: input.managerId },
      });

      if (!manager) {
        return createErrorResponse('客户经理不存在');
      }

      // 验证旧密码
      const isOldPasswordValid = await bcrypt.compare(input.oldPassword, manager.passwordHash);
      if (!isOldPasswordValid) {
        return createErrorResponse('原密码错误');
      }

      // 加密新密码
      const saltRounds = 10;
      const newPasswordHash = await bcrypt.hash(input.newPassword, saltRounds);

      // 更新密码
      await prisma.manager.update({
        where: { id: input.managerId },
        data: { passwordHash: newPasswordHash },
      });

      return createSuccessResponse(null, '密码修改成功');
    } catch (error) {
      console.error('修改密码失败:', error);
      return createErrorResponse('修改密码失败');
    }
  }
}
